package com.app.mall.service.impl;

import com.app.mall.dto.CreateGoodsParam;
import com.app.mall.entity.Goods;
import com.app.mall.mapper.GoodsMapper;
import com.app.mall.dto.GetGoodsParam;
import com.app.mall.service.GoodsService;
import com.app.mall.utils.IdGeneratorSnowflake;
import com.app.mall.vo.GoodsVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: zengtaiyang
 * @Date: 2021/4/13 14:36
 * @Version: 1.0
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private IdGeneratorSnowflake idGeneratorSnowflake;

    @Override
    public Object getList(GetGoodsParam param) {
        LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getGoodsName())) {
            lambdaQueryWrapper.like(Goods::getGoodsName, param.getGoodsName());
        }
        List<GoodsVo> list = page(new Page<>(param.getPageNum(), param.getPageSize()), lambdaQueryWrapper).getRecords().stream().map(p -> {
            GoodsVo vo = new GoodsVo();
            BeanUtils.copyProperties(p, vo);
            return vo;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Object insert(CreateGoodsParam param) {
        return save(new Goods().setId(idGeneratorSnowflake.snowflakeId()).setGoodsName(param.getGoodsName()).setGoodsPrice(param.getGoodsPrice()).setStock(param.getStock()));
    }

}
